//
//  KKTextView.m
//  YZSJTraceBack
//
//  Created by 程强 on 16/5/23.
//  Copyright © 2016年 程强. All rights reserved.
//

#import "KKTextView.h"

@interface KKTextView()
@property (nonatomic,weak) UILabel *placeholderLabel;
@end

@implementation KKTextView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    if(self) {
        
        self.backgroundColor= [UIColor clearColor];
        [self addPlaceHolderLbl];
    }
    return self;
}
- (void)addPlaceHolderLbl
{
    UILabel *placeholderLabel = [[UILabel alloc]init];//添加一个占位label
    
    placeholderLabel.backgroundColor= [UIColor clearColor];
    
    placeholderLabel.numberOfLines=0; //设置可以输入多行文字时可以自动换行
    
    [self addSubview:placeholderLabel];
    
    self.placeholderLabel= placeholderLabel; //赋值保存
    
    self.placeholderColor= [UIColor lightGrayColor]; //设置占位文字默认颜色
    
    self.font= [UIFont systemFontOfSize:15]; //设置默认的字体
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self]; //通知:监听文字的改变

}
- (void)awakeFromNib
{
    [self addPlaceHolderLbl];
}
#pragma mark -监听文字改变
- (void)textDidChange {
    self.placeholderLabel.hidden = self.hasText;
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    [self.placeholderLabel setFrame:CGRectMake(5, 2, self.bounds.size.width-10, 30)];
}
- (void)setPlaceholder:(NSString*)placeholder{
    
    _placeholder= [placeholder copy];
    
    //设置文字
    
    self.placeholderLabel.text= placeholder;
    
    //重新计算子控件frame
    
    [self setNeedsLayout];
    
}
- (void)setPlaceholderColor:(UIColor*)placeholderColor{
    
    _placeholderColor= placeholderColor;
    
    //设置颜色
    
    self.placeholderLabel.textColor= placeholderColor;
    
}
//重写这个set方法保持font一致

- (void)setFont:(UIFont*)font
{
    [super setFont:font];
    self.placeholderLabel.font= font;
    //重新计算子控件frame
    [self setNeedsLayout];
}
- (void)setText:(NSString*)text{
    
    [super setText:text];
    
    [self textDidChange]; //这里调用的就是 UITextViewTextDidChangeNotification 通知的回调
    
}
- (void)setAttributedText:(NSAttributedString*)attributedText
{
    
    [super setAttributedText:attributedText];
    
    [self textDidChange]; //这里调用的就是UITextViewTextDidChangeNotification 通知的回调
    
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:UITextViewTextDidChangeNotification];
    
}
@end
